package com.woniu.account.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.woniu.account.dto.admin.AdminDto;
import com.woniu.account.form.admin.*;
import com.woniu.account.model.Admin;
import com.woniu.account.param.admin.AdminLoadParam;
import com.woniu.account.param.admin.AdminLoginParam;
import com.woniu.account.service.AdminService;
import com.woniu.exception.admin.AdminException;
import com.woniu.exception.admin.AdminExceptionCode;
import com.woniu.model.Result;
import com.woniu.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月11日
 */
@Api(tags = "平台管理员信息")
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MD5Util md5Util;

    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody AdminLoginFrom from)throws Exception{
        HttpServletResponse response = WebUtil.getResponse();
        AdminDto adminDto=adminService.login(BeanUtil.toBean(from, AdminLoginParam.class));
        HashMap<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("admin", adminDto);
        String refreshToken= JwtUtil.createAdminToken(tokenMap,24*60);
        String accessToken= JwtUtil.createAdminToken(tokenMap,30);
        response.setHeader("token",accessToken);
        //存进redis
        redisUtil.set(accessToken,refreshToken,24*60*60);
        return Result.getResult().setData(adminDto).setMsg("登陆成功");
    }
    @ApiOperation("加载所有管理员")
    @PostMapping("/loadAdmins.api")
    public Result load(@RequestBody AdminLoadFrom from)throws Exception{
        PageInfo<AdminDto> adminDtoPageInfo=adminService.load(BeanUtil.toBean(from, AdminLoadParam.class));
        return Result.getResult().setData(adminDtoPageInfo).setMsg("查询成功");
    }

    @ApiOperation("修改管理员的状态")
    @GetMapping("/changeState/{adminId}/{state}.api")
    public Result changeState(@PathVariable(value = "adminId") Integer adminId,@PathVariable("state") Integer state) throws Exception {
        String token = WebUtil.getToken();
        String refreshToken = redisUtil.get(token);
        AdminDto admin = (AdminDto) JwtUtil.getAdmin(refreshToken);
        if (admin.getAdminId()== adminId) throw new AdminException(AdminExceptionCode.ADMIN_CANNOT_CHANGE);
        adminService.changeState(adminId,state);
        return Result.getResult().setMsg("修改状态成功");
    }

    @ApiOperation("新增场馆管理员")
    @PostMapping("/addAdminAccount.api")
    public Result addAdminAccount(@RequestBody AddAdminForm form) throws Exception {
        AdminDto adminDto= adminService.addAdmin(BeanUtil.toBean(form, AddAdminParam.class));
        return Result.getResult().setData(adminDto).setMsg("新增管理员成功");
    }

    @ApiOperation("修改场馆管理员信息")
    @PostMapping("/updateAdmin.api")
    public Result updateAdminAccount(@RequestBody UpdateAdminForm form) throws Exception {
        boolean b = adminService.updateById(BeanUtil.toBean(form, Admin.class));
        if (!b) throw new AdminException(AdminExceptionCode.ADMIN_CHANGE_FAIL);
        AdminDto adminDto = BeanUtil.toBean(adminService.getById(form.getAdminId()), AdminDto.class);
        return Result.getResult().setData(adminDto).setMsg("修改成功");
    }


    @ApiOperation("加载管理员自己的信息")
    @PostMapping("/loadAccount.api")
    public Result loadAccount() throws Exception {
        String token = WebUtil.getToken();
        String s = redisUtil.get(token);
        AdminDto adminDto = JSONUtil.toBean(JSONUtil.toJsonStr(JwtUtil.getAdmin(s)),AdminDto.class);
        Admin admin = adminService.getById(adminDto.getAdminId());
        if (ObjectUtil.isEmpty(admin)) throw new AdminException(AdminExceptionCode.ADMIN_NOT_EXIST);
        AdminDto accountLoginDto = BeanUtil.toBean(admin, AdminDto.class);
        return Result.getResult().setData(accountLoginDto).setMsg("查询成功");
    }

    /**
     * 发送修改密码的验证码
     * @param form
     * @return
     * @throws Exception
     */

    @ApiOperation("修改密码")
    @PostMapping("/updateAdminPass.api")
    public Result updateAdminPass(@RequestBody UpdateAdminPassForm form) throws Exception {
        String token = WebUtil.getResponse().getHeader("token");
        String s = redisUtil.get(token);
        AdminDto adminDto = (AdminDto) JwtUtil.getAdmin(s);
        Admin account = adminService.getById(adminDto.getAdminId());
        if (ObjectUtil.isEmpty(account)) throw new AdminException(AdminExceptionCode.ADMIN_NOT_EXIST);
        String s1 = redisUtil.get(RedisKeyUtil.registerCodeKey(account.getAdminPhone()));
        if(!s1.equals(form.getCode())) throw new AdminException(500,"验证码错误");
        String newPwd = md5Util.encryption(account.getAdminPhone(), form.getAdminPass());
        if (newPwd.equals(account.getAdminPassword())) throw new AdminException(500,"新旧密码不能一致");
        account.setAdminPassword(newPwd);
        boolean b = adminService.updateById(account);
        if (!b) throw new AdminException(AdminExceptionCode.ADMIN_CHANGE_FAIL);
        return Result.getResult().setMsg("修改成功");
    }
}

